/*
 * Copyright (C) 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.zxing.client.android;

/*import it.intecs.GestureIntents;
import it.intecs.ActivitiesMenu;
import it.intecs.SliceGestureListener;
import it.intecs.SpeechManager;
import it.intecs.main;*/

import it.intecs.pisa.smarcos.R;
import it.intecs.pisa.smarcos.activities.BaseActivity;
import it.intecs.pisa.smarcos.base.SpeechManager;
import it.intecs.pisa.smarcos.util.ContextUtils;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.google.zxing.ResultMetadataType;
import com.google.zxing.client.android.camera.CameraManager;
import com.google.zxing.client.android.result.ResultHandler;
import com.google.zxing.client.android.result.ResultHandlerFactory;

/**
 * The barcode reader activity itself. This is loosely based on the CameraPreview
 * example included in the Android SDK.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 * @author Sean Owen
 */
public final class CaptureActivity extends BaseActivity implements SurfaceHolder.Callback {
	
  public static final String INTENT_SHOW="com.google.zxing.client.android.CaptureActivity.SHOW";	
  
  private static final String TAG = CaptureActivity.class.getSimpleName();
  private static final long BULK_MODE_SCAN_DELAY_MS = 1000L;

  private static final Set<ResultMetadataType> DISPLAYABLE_METADATA_TYPES;
  static {
    DISPLAYABLE_METADATA_TYPES = new HashSet<ResultMetadataType>(5);
    DISPLAYABLE_METADATA_TYPES.add(ResultMetadataType.ISSUE_NUMBER);
    DISPLAYABLE_METADATA_TYPES.add(ResultMetadataType.SUGGESTED_PRICE);
    DISPLAYABLE_METADATA_TYPES.add(ResultMetadataType.ERROR_CORRECTION_LEVEL);
    DISPLAYABLE_METADATA_TYPES.add(ResultMetadataType.POSSIBLE_COUNTRY);
  }

   
  private CaptureActivityHandler handler;
  private ViewfinderView viewfinderView;
  
  private View view;
  private LinearLayout superCenterView;
  private ViewGroup baseCenterView;
  LayoutInflater inflater;
  private ContextUtils cUtils;
   
  private boolean hasSurface;
  private Vector<BarcodeFormat> decodeFormats;
  private String characterSet;
  //private Result lastResult;
  private CharSequence displayContents = "";
  //private boolean copyToClipboard;
  //private HistoryManager historyManager;
  private InactivityTimer inactivityTimer;
  private Vibrator vibrator;
  private BeepManager beepManager;
  private SpeechManager speechManager;
 
  ViewfinderView getViewfinderView() {
    return viewfinderView;
  }

  public Handler getHandler() {
    return handler;
  }

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    
    speechManager = SpeechManager.getInstance(getApplicationContext());
    
    cUtils = new ContextUtils(getApplicationContext());
    inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
	view = inflater.inflate(cUtils.retrieveRvalue("layout", "qr_reader"), null);
    
    // Metodo di BaseViewManager
	Init(getBaseContext());
	setC(R.string.QR_Button_C);
	setD(R.string.QR_Button_D);
	setContentView(getBaseView());
	
	LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -1, 0.3f);
	superCenterView = (LinearLayout) findViewById(R.id.super_center_base_view);
	superCenterView.setLayoutParams(params);
	
	baseCenterView = (ViewGroup) findViewById(R.id.center_base_view);
	baseCenterView.addView(view);
   	
    CameraManager.init(getApplication());
    viewfinderView = (ViewfinderView) view.findViewById(R.id.viewfinder_view);
   	viewfinderView.setOnTouchListener(listener);
    
    handler = null;
    //lastResult = null;
    hasSurface = false;
    inactivityTimer = new InactivityTimer(this);
    beepManager = new BeepManager(this);
    vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);  
   }

  @Override
  protected void onResume() {
    super.onResume();
    resetStatusView();
 
    SurfaceView surfaceView = (SurfaceView) view.findViewById(R.id.preview_view);
     SurfaceHolder surfaceHolder = surfaceView.getHolder();
    if (hasSurface) {
      // The activity was paused but not stopped, so the surface still exists. Therefore
      // surfaceCreated() won't be called, so init the camera here.
      initCamera(surfaceHolder);
    } else {
      // Install the callback and wait for surfaceCreated() to init the camera.
      surfaceHolder.addCallback(this);
      surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    final Vector<BarcodeFormat> QR_CODE_FORMATS;
    QR_CODE_FORMATS = new Vector<BarcodeFormat>(1);
    QR_CODE_FORMATS.add(BarcodeFormat.QR_CODE);
    decodeFormats = QR_CODE_FORMATS;
    characterSet = null; 
      
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    //copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);

    beepManager.updatePrefs();
  }

  @Override
  protected void onPause() {
    super.onPause();
    if (handler != null) {
      handler.quitSynchronously();
      handler = null;
    }
 
    CameraManager.get().closeDriver();
    speechManager.say(getString(R.string.TTS_Camera_closed), true, false);   
  }

  @Override
  public void onDestroy() {
    inactivityTimer.shutdown();
    super.onDestroy();
    
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-2, -2, 0);
	superCenterView.setLayoutParams(params);
  }

  
	// BACK
	@Override
	public void onClick_A(){
		Log.d(TAG, "onClick_A");
		
		Intent returnIntent;
		returnIntent=new Intent("it.intecs.pisa.smarcos.services.ResultReceiver.SHOW");
		returnIntent.putExtra("Result", "NORESULT");
		returnIntent.addCategory(Intent.CATEGORY_DEFAULT);					
		sendBroadcast(returnIntent);
		sentResult = true;
		vibrator.vibrate(300);
		finish();	
	}

	// POSITION
	@Override
	public void onClick_B(){
		Log.d(TAG, "onClick_B");	
		speechManager.say(getString(R.string.MV_Main_QR_Voice), true, false);	
	}

	//SEARCH AGAIN
	@Override
	public void onClick_C(){
		Log.d(TAG, "onClick_C");
		
		displayContents = "";
		resetStatusView();
		if (handler != null) {
			handler.sendEmptyMessage(R.id.restart_preview);
		}
		speechManager.say(getString(R.string.TTS_QR_Again), true, false);
	}
	
	// REPEAT 
	@Override
	public void onClick_D(){
		Log.d(TAG, "onClick_D");
	
		if (displayContents != null && displayContents.length() != 0 )
			speechManager.say(displayContents.toString(), true, false);
		else
			speechManager.say(getString(R.string.TTS_QR_Buffer_Empty), true, false);
	}

	/*@Override
	public void onClick_Center(MotionEvent event){
		Log.d(TAG, "onClick_Center");
	}*/
  
  public void surfaceCreated(SurfaceHolder holder) {
    if (!hasSurface) {
      hasSurface = true;
      initCamera(holder);
    }
  }

  public void surfaceDestroyed(SurfaceHolder holder) {
    hasSurface = false;
  }

  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

  }

 
  public void handleDecode(Result rawResult, Bitmap barcode) {
	  inactivityTimer.onActivity();
	  //lastResult = rawResult;
	  beepManager.playBeepSoundAndVibrate();

	  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
	  if (prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, false)) {
		  Toast.makeText(this, R.string.msg_bulk_mode_scanned, Toast.LENGTH_SHORT).show();
		  // Wait a moment or else it will scan the same barcode continuously about 3 times
		  if (handler != null) {
			  handler.sendEmptyMessageDelayed(R.id.restart_preview, BULK_MODE_SCAN_DELAY_MS);
		  }
		  resetStatusView();         
	  } else {

		  handleDecodeInternally(rawResult, barcode);
	  }
  }

 
  private void handleDecodeInternally(Result rawResult, Bitmap barcode) {
	
	    viewfinderView.setVisibility(View.GONE);
	    //qrMenuView.setVisibility(View.VISIBLE);
	    	    
	    ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
	    displayContents = resultHandler.getDisplayContents();
	 
	    //TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
	    //contentsTextView.setText(displayContents);
	    TextView resultView = (TextView) findViewById(R.id.result_view);
	    resultView.setVisibility(View.VISIBLE);
	    resultView.setText(displayContents);
	    // Crudely scale betweeen 22 and 32 -- bigger font for shorter text
	    int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
	    //contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
	    resultView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
	    
	    speechManager.say(displayContents.toString(), false, false);
	    resultView.setVisibility(View.GONE);
	  }
  
  
  
  /*private class QRMenuBroadcastReceiver extends BroadcastReceiver
  {
	private final String TAG = QRMenuBroadcastReceiver.class.getSimpleName();  
	 
  	Activity activity;
  	ActivitiesMenu matrixPad;
  	int matrixIndexI = -1;
  	TextView menu_voice_view;
	final Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); 
	
  	public QRMenuBroadcastReceiver(Activity act){
  		activity = act;
  		matrixPad = new ActivitiesMenu(act);
  	}
  	
  	@Override
  	public void onReceive(Context arg0, Intent intent) {
  		
  		boolean gestureChoise = false;
		int matrixValue = 0;
		int menuLength = matrixPad.getDimension(R.id.QR_MENU_MATRIX);
		String intentStr;

		intentStr=intent.getAction();
		
		if(intentStr.equals(GestureIntents.INTENT_GESTURE_UP)){	
			finish();
			return;
		}
		
		
   		if (matrixIndexI == - 1){
			matrixValue = matrixPad.menuHandler(R.id.QR_MENU_MATRIX, matrixIndexI, matrixIndexI++, gestureChoise);
			return;
		}
					
		if(intentStr.equals(GestureIntents.INTENT_GESTURE_RIGHT)){

			if (matrixIndexI != menuLength - 1)
				matrixValue = matrixPad.menuHandler(R.id.QR_MENU_MATRIX, matrixIndexI, ++matrixIndexI, gestureChoise);
			else    		
				matrixValue = matrixPad.menuHandler(R.id.QR_MENU_MATRIX, matrixIndexI, matrixIndexI, gestureChoise);
			return;
		}	

		if(intentStr.equals(GestureIntents.INTENT_GESTURE_LEFT)){

			if (matrixIndexI != 0)
				matrixValue = matrixPad.menuHandler(R.id.QR_MENU_MATRIX, matrixIndexI, --matrixIndexI, gestureChoise);
			else		
				matrixValue = matrixPad.menuHandler(R.id.QR_MENU_MATRIX, matrixIndexI, matrixIndexI, gestureChoise);

			return;
		}	


		if(intentStr.equals(GestureIntents.INTENT_GESTURE_CHOICE)){

			gestureChoise = true;
			matrixValue = matrixPad.menuHandler(R.id.QR_MENU_MATRIX, matrixIndexI, matrixIndexI, gestureChoise);	
			vibrator.vibrate(300);
				
				switch (matrixValue) {
				case R.string.TTS_QR_Again: {
					Log.d(TAG, "onReceive TTS_QR_Again");
					resetStatusView();
					if (handler != null) {
						handler.sendEmptyMessage(R.id.restart_preview);
					}
					break;
				}
				case R.string.TTS_QR_Save: {
					Log.d(TAG, "onReceive TTS_PR_Save");
					//TO DO
					break;
				}
				}
			}
		}
  	}*/

  
 
  // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
  /*private void handleDecodeExternally(Result rawResult, Bitmap barcode) {
    viewfinderView.drawResultBitmap(barcode);

    // Since this message will only be shown for a second, just tell the user what kind of
    // barcode was found (e.g. contact info) rather than the full contents, which they won't
    // have time to read.
    ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
  //INTECS CHANGE - BEGIN
    //statusView.setText(getString(resultHandler.getDisplayTitle()));
  //INTECS CHANGE - END

    if (copyToClipboard) {
      ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
      clipboard.setText(resultHandler.getDisplayContents());
    }

    if (source == Source.NATIVE_APP_INTENT) {
      // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
      // the deprecated intent is retired.
      Intent intent = new Intent(getIntent().getAction());
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
      intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
      intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
      Message message = Message.obtain(handler, R.id.return_scan_result);
      message.obj = intent;
      handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
    } else if (source == Source.PRODUCT_SEARCH_LINK) {
      // Reformulate the URL which triggered us into a query, so that the request goes to the same
      // TLD as the scan URL.
      Message message = Message.obtain(handler, R.id.launch_product_query);
      int end = sourceUrl.lastIndexOf("/scan");
      message.obj = sourceUrl.substring(0, end) + "?q=" +
          resultHandler.getDisplayContents().toString() + "&source=zxing";
      handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
    } else if (source == Source.ZXING_LINK) {
      // Replace each occurrence of RETURN_CODE_PLACEHOLDER in the returnUrlTemplate
      // with the scanned code. This allows both queries and REST-style URLs to work.
      Message message = Message.obtain(handler, R.id.launch_product_query);
      message.obj = returnUrlTemplate.replace(RETURN_CODE_PLACEHOLDER,
          resultHandler.getDisplayContents().toString());
      handler.sendMessageDelayed(message, INTENT_RESULT_DURATION);
    }
  }
*/
 
  private void initCamera(SurfaceHolder surfaceHolder) {
	  try {
      CameraManager.get().openDriver(surfaceHolder);
      speechManager.say(getString(R.string.TTS_Camera_opened), false, false);

    } catch (IOException ioe) {
      Log.w(TAG, ioe);
      //displayFrameworkBugMessageAndExit();
      return;
    } catch (RuntimeException e) {
      // Barcode Scanner has seen crashes in the wild of this variety:
      // java.?lang.?RuntimeException: Fail to connect to camera service
      Log.w(TAG, "Unexpected error initializating camera", e);
      //displayFrameworkBugMessageAndExit();
      return;
    }
 
    if (handler == null) {
      handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
    }
  }

  private void resetStatusView() {
	  viewfinderView.setVisibility(View.VISIBLE);
	  //lastResult = null;
  }

  public void drawViewfinder() {
    viewfinderView.drawViewfinder();
  }
}
